const db = wx.cloud.database()
const _ = db.command
Page({

    /**
     * 页面的初始数据
     */
    data: {
        time:'',
        titid:'',
        title: '',
        mood: '',
        content: '',
        tempFilePaths: [],
        biglist: [],
        zonename: '',
        address: '',
        addressname: '',
        latitude: '',
        longitude: '',
    },
    //发布
    comsend: function () {
        let that = this;
        this.gettime();
        this.uploadPhotoToDatabase().then(val => {
            setTimeout(function () {
                that.sharetext();
            }, 10000)
        })
        wx.showToast({
            title: '正在发布...',
            icon: 'loading',
            mask: true,
            duration: 9500
        })
    },
    //上传数据
    sharetext: function () {
        // this.uploadPhotoToDatabase();
        let user = wx.getStorageSync('user')
        let phone = user.phone;
        let name = user.name;
        let userimg = user.userimg;
        let titid= this.data.titid;
        let time= this.data.time;
        let title = this.data.title;
        let mood = this.data.mood;
        let content = this.data.content;
        let img = this.data.images_fileID;
        // let zonename = this.data.zonename;
        let address = this.data.address;
        let addressname = this.data.addressname;
        let latitude = this.data.latitude;
        let longitude = this.data.longitude;
        // console.log(title, mood, content);
        console.log("点击了发布");
        console.log("图片", img);
        //添加发布内容到公共数据集合
        db.collection('my_share').where({
            phone: phone
        }).get({
            success(res) {
                console.log("获取数据成功");
                let user = res.data[0]
                if (user && phone == user.phone) {
                    db.collection('my_share')
                        .where({
                            // openID: wxContext.OPENID,
                            phone: phone
                        })
                        .update({
                            data: {
                                userimg: userimg,
                                name: name,
                                issue: _.unshift(
                                    {
                                        title: title,
                                        titid:titid,
                                        time:time,
                                        mood: mood,
                                        content: content,
                                        img: img,
                                        address: address,
                                        addressname: addressname,
                                        latitude: latitude,
                                        longitude: longitude,
                                        isDel:false,
                                        collcount:0
                                    }
                                )
                            },
                            success(res) {
                                console.log('发布成功', res)
                                wx.showToast({
                                    title: '发布成功',
                                })
                                setTimeout(function () {
                                    wx.switchTab({
                                        url: '/mypages/index/index',
                                    })
                                }, 1000)
                            },
                            fail(res) {
                                console.log('发布失败', res)
                            }
                        })
                } else if (!user) {
                    db.collection('my_share')
                        .add({
                            data: {
                                userimg: userimg,
                                name: name,
                                phone: phone,
                                issue: [
                                    {
                                        phone: phone,
                                        title: title,
                                        titid:title,
                                        time:time,
                                        mood: mood,
                                        content: content,
                                        img: img,
                                        address: address,
                                        addressname: addressname,
                                        latitude: latitude,
                                        longitude: longitude,
                                        isDel:false,
                                        collcount:0
                                    }
                                ]

                            },
                            success(res) {
                                console.log('发布成功', res)
                                wx.showToast({
                                    title: '发布成功',
                                })
                                setTimeout(function () {
                                    wx.switchTab({
                                        url: '/mypages/index/index',
                                    })
                                }, 1000)

                            },
                            fail(res) {
                                console.log('发布失败', res)
                            }
                        })
                }
            },
            fail(res) {
                console.log("没有数据");

            }
        })

    },
    //上传图片
    addimg: function () {
        // wx.chooseMedia({
        //     count: 9,
        //     mediaType: ['image', 'video'],
        //     sourceType: ['album', 'camera'],
        //     sizeType: ['original', 'compressed'],
        //     maxDuration: 30,
        //     camera: 'back',
        //     success: res => {
        //         console.log(res)
        //         var photoTempPath = res.tempFiles[0].tempFilePath
        //         // this.uploadPhotoToDatabase(photoTempPath)
        //     }
        // })
        let that = this;
        wx.chooseMedia({
            count: 9, // 默认最多9张图片，可自行更改
            mediaType: ['image', 'video'],
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            maxDuration: 30,
            camera: 'back',
            success: res => {
                wx.showToast({
                    title: '正在上传...',
                    icon: 'loading',
                    mask: true,
                    duration: 1000
                })
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                // let tempFilePath = res.tempFiles;
                console.log(res);
                let tem = that.data.tempFilePaths
                let tempFilePath = res.tempFiles.map
                    (item => {
                        return item.tempFilePath;
                    })
                tem = tem.concat(tempFilePath)
                console.log(tem);
                console.log(tempFilePath);
                that.setData({
                    tempFilePaths: tem
                })

            }
        })
    },
    //将图片上传至云存储
    uploadPhotoToDatabase: function () {
        var that = this;
        // let id = this.data.id;
        // let phone = this.data.phone;
        // wx.cloud.uploadFile({
        //     cloudPath: "save/" + Date.now() + ".jpg",
        //     filePath: photoTempPath
        // })
        var count = 0;
        var h = this.data.tempFilePaths.length;
        if (h != 0) {
            this.setData({
                images_fileID: []
            })
        }
        for (var i = 0; i < h; i++) {
            //上传文件
            var imageUrl = that.data.tempFilePaths[i].split("/");
            var name = imageUrl[imageUrl.length - 1];
            var images_fileID = that.data.images_fileID;
            wx.cloud.uploadFile({
                cloudPath: "save/" + Date.now() + ".jpg",    //自定义云存储路径
                filePath: that.data.tempFilePaths[i],

            }).then(res => {
                images_fileID = images_fileID.concat([res.fileID])
                console.log("看看", images_fileID);
                // images_fileID.push(res.fileID);
                that.setData({
                    images_fileID: images_fileID        //更新data中的 fileID
                })
            })
        }
        return Promise.resolve(/* 这里是需要返回的数据*/)
    },
    //预览图片
    PreviewImg: function (e) {
        let index = e.target.dataset.index;
        let that = this;
        console.log(that.data.tempFilePaths[index]);
        //console.log(that.data.tempFilePaths);
        wx.previewImage({
            current: that.data.tempFilePaths[index],
            urls: that.data.tempFilePaths,
        })

    },
    //长按删除图片
    DeleteImg: function (e) {
        var that = this;
        var tempFilePaths = that.data.tempFilePaths;
        var index = e.currentTarget.dataset.index;//获取当前长按图片下标
        wx.showModal({
            title: '提示',
            content: '确定要删除此图片吗？',
            success: function (res) {
                if (res.confirm) {
                    //console.log('点击确定了');
                    tempFilePaths.splice(index, 1);
                } else if (res.cancel) {
                    //console.log('点击取消了');
                    return false;
                }
                that.setData({
                    tempFilePaths
                });
            }
        })
    },
    //模糊配对地区
    zonemate() {
        let biglist = this.data.biglist
        for (var i = 0; i < biglist.length; i++) {
            var num = this.data.content.indexOf(biglist[i].zonename)
            if (num != -1) {
                this.setData({
                    zonename: biglist[i].zonename
                })
            }
        }
    },
    //添加地点
    addArea() {
        let that = this;
        wx.getLocation({
            type: "gcj02",
            success(res) {
                wx.chooseLocation({
                    latitude: res.latitude,
                    longitude: res.longitude,
                    success: function (data) {
                        console.log(data)
                        that.setData({
                            address: data.address,
                            addressname: data.name,
                            latitude: data.latitude,
                            longitude: data.longitude,
                        })
                    },
                    fail(res){
                        console.log(res);
                    }
                })
            },
            fail(res){
                console.log(res);
            }
        })
    },
    useinput:function(){},
    //添加时间和文章id
    gettime:function(){
        var titid = Number(Math.random().toString().substr(3, 10) + Date.now()).toString(36);
        var mydate = new Date();
        var year = mydate.getFullYear();
        var month = mydate.getMonth() + 1 < 10 ? '0' + mydate.getMonth() + 1 : mydate.getMonth() + 1;
        var dat = mydate.getDate() < 10 ? '0' + mydate.getDate() : mydate.getDate();
        this.setData({
            time: year + '.' + month + '.' + dat,
            titid:titid,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let user = wx.getStorageSync('user')
        if (!user) {

            wx.showModal({
                title: '未登录',
                content: '确定现在去登录吗？',
                success: function (res) {
                    if (res.confirm) {
                        wx.switchTab({
                            url: '/mypages/my/my',
                        })
                    } else if (res.cancel) {
                        //console.log('点击取消了');
                        wx.switchTab({
                            url: '/mypages/index/index',
                        })

                    }
                    that.setData({
                        tempFilePaths
                    });
                }
            })
        }

        // wx.cloud.callFunction({
        //     name: 'home',
        //     // config: {
        //     //   env: 'cloud1-0gynot18c71f42a8'
        //     // },
        //     data: {
        //         type: 'place'
        //     }
        // }).then((resp) => {
        //     //   console.log(resp.result.data);
        //     this.setData({
        //         biglist: resp.result.data
        //     });
        // }).catch((e) => {
        //     console.log(e);

        // });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})